<script setup lang="ts">
import {reactive,watch,getCurrentInstance} from 'vue'
import {DemandInfoTradingUnitApi,} from "@/api/dd/demandinfotradingunit";
import {ElMessageBox} from "element-plus";
import {DemandInfoMainApi} from "@/api/dd/demandinfomain";
import {formatToDate} from "@/utils/dateUtil";
import {DemandInfoTradingUnitInformationVO, DemandInfoTradingUnitInformationApi} from '@/api/dd/demandinfotradingunitinformation'

const props = defineProps({
  mainId: {
    type: Number,
    default: 0
  },
  tradingUnitId: {
    type: Number,
    default: 0
  },
  zhuanrangriqiList: {
    type: Array,
    default: () => []
  },
  tableList: {
    type: Array,
    default: () => []
  },
  formDataId: {
    type: Number,
    default: 0
  },
  formType: {
    type: Number,
    default: 0
  }
})

const emits = defineEmits(['getDateList', 'getDataList','updateFengValue', 'submitForm'])

// 选中的转让日期
const zhuanrangriqiValue = ref('')

const dataForm = reactive({
  value1: [],
  size: 10,
  value2: [],
  size: 10,
})

const dataFormList: any = reactive({
  data: []
})

const tableListd: any = ref([])

watch(() => props.tableList, (newVal) => {
  // console.log(newVal, 'newVal')
  dataFormList.data = newVal.filter(item => item)
  // console.log(dataFormList.data, 'dataFormList.data')
  dataFormList.data = dataFormList.data.map(item => {
    return {
      ...item,
      datedd: item.transferDateStart + '-' + item.transferDateEnd
    }
  })
  tableListd.value = dataFormList.data
})

// 添加日期
const addDate = async () => {
  console.log(props, 'props')
  const data = {
    mainId: props.mainId,
    tradingUnitId: props.tradingUnitId
  }
  const res = await DemandInfoTradingUnitApi.createDemandInfoTradingUnit(data)
  // console.log(res, 'res')
  if (isNaN(parseInt(res))) {
    // debugger
    ElMessageBox.confirm('添加日期失败', '提示', {
      confirmButtonText: '确 认',
      cancelButtonText: '取 消'
    })
    return false
  }

  emits('getDateList')
  emits('getDataList')
  emits('submitForm', 4, true)

  // dataFormList.data.push({
  //   tableData: [],
  //   tradingUnitId: props.tradingUnitId,
  //   transferDateStart: '',// 转让日期
  //   transferDateEnd: '',// 转让日期
  //   type: 2,
  //   radio: '1',
  //   change: (val, item) => {
  //     if (val === '1') {
  //       item.notTrading = ''
  //     } else {
  //       item.participateTradingId = null
  //     }
  //   },
  //   participateTradingId: null,
  //   notTrading: null,
  //   expectedDate: '', // 预计操作日期
  //   actualAmount: '', // 实际操作金额
  // })
}

const message = useMessage() // 消息弹窗


// 定义加载实例
let loadingInstance = null;

const { proxy } = getCurrentInstance()

// 查询指定表格
const handlerSearch = async (item, index, type, isCheck = true) => {
  if(type == 2){
  // 显示加载图标
  loadingInstance = ElLoading.service({
      lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  }


  try {
    // 直接更新 dataFormList.data 中的数据
    dataFormList.data[index].transferDateStart = item.transferDateStart;
    dataFormList.data[index].transferDateEnd = item.transferDateEnd;
    dataFormList.data[index].expectedDate = item.expectedDate;
    dataFormList.data[index].actualAmount = item.actualAmount;
    dataFormList.data[index].radio = item.radio;
    dataFormList.data[index].notTrading = item.notTrading;
    dataFormList.data[index].participateTradingId = item.participateTradingId;
    // 查询数据
    let newItem = JSON.parse(JSON.stringify(item))
    // console.log(newItem.transferDateStart, 'newItem.transferDateStart')
    if (newItem.transferDateStart) {
      newItem.transferDateStart = formatToDate(newItem.transferDateStart)
    }
    if (newItem.transferDateEnd) {
      newItem.transferDateEnd = formatToDate(newItem.transferDateEnd)
    }
    delete newItem.radio
    delete newItem.change
    newItem.id = item.id
    newItem.mainId = item.mainId
    newItem.tradingUnitId = props.tradingUnitId
    newItem.actualAmount = item.actualAmount ? item.actualAmount : ''
    // console.log(newItem, 'newItem newItem')
    if(newItem.notTrading == null && newItem.participateTradingId == null){
      if (isCheck) {
        proxy.$showErrorMessage.error('请填写转让对象或请先点击查询')
      }
      return false
    }
    // TODD request data  =>  newItem
    // console.log(newItem, 'newItem 查询指定表格')
    // console.log(newItem,'newItem')
    nextTick(async () => {
      await DemandInfoTradingUnitApi.updateDemandInfoTradingUnit(newItem)
      // console.log(result, 'result result')
      DemandInfoMainApi.getDemandInfoMain(item.mainId).then(res => {
        const targetItem = res.demandInfoTradingUnitMapList.find(unit => unit.id === item.id);
        console.log(targetItem)
        item.demandInfoTradingUnitInformationControllers = targetItem.demandInfoTradingUnitDO[index].demandInfoTradingUnitInformationControllers
      })
      // message.success('添加成功')
      if (!type) {
        emits('getDateList')
        emits('getDataList')
      }
    })
  } catch (error) {
    console.error('查询出错:', error);
    message.error('查询失败，请稍后重试');
  } finally {
    // 关闭加载图标
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
}

// 删除指定表格
const handlerDelete = (item,index) => {
  console.log(item, 'item')
  // 直接更新 dataFormList.data 中的数据
  DemandInfoTradingUnitApi.deleteDemandInfoTradingUnit(item.id).then(res => {
    // 查询数据
  dataFormList.data.splice(index, 1)
  })

}

// 重置筛选条件
const resetData = () => {
  dataForm.value1 = []
}

// 锚点跳转
const scrollToAnchor = (anchorId) => {
  if (!anchorId) return false
  const target = document.getElementById(`${anchorId}`);
  if (target) {
    target.scrollIntoView({ behavior: 'smooth' });
  }
};
// 根据时段返回对应的颜色
const getTimePeriodColor = (timePeriod: string) => {
  const peakPeriods = ['07:00-08:00','08:00-09:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00', '22:00-23:00'];
  const offPeakPeriods = ['09:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00'];
  const valleyPeriods = ['00:00-01:00', '01:00-02:00', '02:00-03:00', '03:00-04:00', '04:00-05:00', '05:00-06:00', '06:00-07:00', '23:00-00:00'];

  if (peakPeriods.includes(timePeriod)) {
    //绿色
    return 'red'; // 高峰时段颜色
  } else if (offPeakPeriods.includes(timePeriod)) {
    return 'green'; // 平峰时段颜色
  } else if (valleyPeriods.includes(timePeriod)) {

    //橘色
    return 'orange'; // 低谷时段颜色
  }
};

// 更新实际操作金额
const updateActualAmount = async (row, item, index) => {

  const totalPrice = item.demandInfoTradingUnitInformationControllers.reduce((sum, row) => {
    // 将 row.electricity 和 row.electricityPrice 转换为数字类型
    const electricity = !isNaN(parseFloat(row.electricity)) ? parseFloat(row.electricity) : 0;
    const electricityPrice = !isNaN(parseFloat(row.electricityPrice)) ? parseFloat(row.electricityPrice) : 0;
    // 计算乘积并累加
     return sum + (electricity*electricityPrice);
  }, 0);

  item.actualAmount = totalPrice.toFixed(2);
  // console.log(item.actualAmount, 'item.actualAmount')
  // 触发查询
  await handlerSearch(item, index)

  // 触发自定义事件，传递必要的数据
  emits('updateFengValue', item.tradingUnitId, row, item);
};

// 处理电量修改事件
const handleElectricityChange = async (row, item, index) => {

  const totalPrice = item.demandInfoTradingUnitInformationControllers.reduce((sum, row) => {
    // 将 row.electricity 和 row.electricityPrice 转换为数字类型
    const electricity = !isNaN(parseFloat(row.electricity)) ? parseFloat(row.electricity) : 0;
    const electricityPrice = !isNaN(parseFloat(row.electricityPrice)) ? parseFloat(row.electricityPrice) : 0;
    // 计算乘积并累加
    return sum + (electricity*electricityPrice);
  }, 0);
  item.actualAmount = totalPrice.toFixed(2);
  // console.log(item.actualAmount, 'item.actualAmount totalPrice')
  // 触发查询
  await handlerSearch(item, index)

  // 触发自定义事件，传递必要的数据
  emits('updateFengValue', item.tradingUnitId, row, item);
};

// 定义一个计算属性，根据 item.type 动态返回 label
const getKmlLabel = (item) => {
  if (item.type === '1') {
    return '可卖量MWh'; // 转入类型
  } else if (item.type === '2') {
    return '可买量MWh'; // 转出类型
  }
  return '系统可买量/可卖量MWh'; // 默认值
};
// 定义函数动态返回 zc 列的 label
const getZcLabel = (item) => {
  if (item.type === '1') {
    return '待操作转出MWh'; // 转入类型
  } else if (item.type === '2') {
    return '待操作转入MWh'; // 转出类型
  }
  return '待操作转入/转出MWh'; // 默认值
};

// 定义函数动态返回 kmml 列的 label
const getKmmlLabel = (item) => {
  if (item.type === '1') {
    return '实际可卖量MWh'; // 转入类型
  } else if (item.type === '2') {
    return '实际可买量MWh'; // 转出类型
  }
  return '实际可买量/可卖量MWh'; // 默认值
};

defineExpose({
  tableList: tableListd,
  dataFormList: dataFormList
})
// 格式化实际操作金额，保留两位小数
const formatActualAmount = (item) => {
  const value = item.actualAmount;
  if (value !== '') {
    const num = parseFloat(value.replace(/[^0-9.]/g, ''));
    if (!isNaN(num)) {
      item.actualAmount = num.toFixed(2);
    } else {
      item.actualAmount = '';
    }
  }
};
</script>

<template>
  <el-row style="padding-bottom: 20px; border-bottom: 2px solid #ccc;">
    <el-col :span="2" class="custom-small-font">转让日期：</el-col>
    <el-col :span="6">
      <el-select v-model="zhuanrangriqiValue" placeholder="转让日期" style="width: 240px">
        <el-option
          v-for="(child, childIndex) in zhuanrangriqiList"
          :key="childIndex"
          :label="child"
          :value="child"
        />
      </el-select>
    </el-col>
    <el-button type="default" class="sub-btn" @click="scrollToAnchor(zhuanrangriqiValue)">跳转</el-button>
    <el-button type="default" class="sub-btn" @click="addDate">添加日期</el-button>
  </el-row>

  <div style="height: 30px;"></div>

  <div style="width: 100%; min-height: 100%; max-height: 100%; overflow-y: auto; border: 1px solid #409eff; padding: 10px; box-sizing: border-box;">
    <div v-for="(item, index) in dataFormList.data" :id="item.datedd" :key="index" style="margin-top: 20px;">
      <el-row style="width: 100%;">
        <el-col :span="2" class="font-color">转让日期：</el-col>
        <el-col :span="10" style=" display: flex; justify-content: flex-start; align-items: center;">
          <el-date-picker
            v-model="item.transferDateStart"
            type="date"
            start-placeholder="开始日期"
            @change="handlerSearch(item, index, 1)"
          />
          <p style="margin: 0 8px;">至</p>
          <el-date-picker
            v-model="item.transferDateEnd"
            type="date"
            end-placeholder="结束日期"
            @change="handlerSearch(item, index, 1)"
          />
        </el-col>
        <el-col :span="2" class="font-color">转让类型：</el-col>
        <el-col :span="10">
          <el-select
v-model="item.type" placeholder="转让类型" style="width: 240px" clearable
                     @change="handlerSearch(item, index, 1)">
            <el-option
              v-for="(child, childIndex) in [{ label: '转入', value: '1' }, { label: '转出', value: '2'}]"
              :key="childIndex"
              :label="child.label"
              :value="child.value"
            />
          </el-select>
        </el-col>
      </el-row>

      <div style="height: 30px;"></div>

      <el-row style="width: 100%; margin-bottom: 20px;" :gutter="24">
    <el-col :span="12">
      <el-radio value="1" v-model="item.radio" @click="item.change(1, item)">
        <div style="display: flex; justify-content: flex-start; align-items: center;">
          <div style="font-size: 16px" class="font-color">参与交易单元：</div>
          <el-select
            v-model="item.participateTradingId"
            placeholder="参与交易单元"
            style="width: 240px"
            :disabled="item.radio === '2'"
            @change="handlerSearch(item, index, 1)"
          >
            <el-option
              v-for="(child, childIndex) in item.canyujiaoyidanyuan"
              :key="childIndex"
              :label="child.name + ' - ' + child.tradingUnit"
              :value="child.id"
            />
          </el-select>
        </div>
      </el-radio>
      &nbsp;&nbsp;&nbsp;&nbsp;
      <el-radio value="2" v-model="item.radio" @click="item.change(2, item)">
        <div style="display: flex; justify-content: flex-start; align-items: center;">
          <div style="font-size: 16px" class="font-color">我方不参与：</div>
          <el-input
            v-model="item.notTrading"
            placeholder="我方不参与"
            :disabled="item.radio === '1'"
            @blur="handlerSearch(item, index, 1)"
          />
        </div>
      </el-radio>
    </el-col>
        <el-col :span="12" style="display: flex; justify-content: flex-start; align-items: center;">
          <div class="font-color">预计操作日期：
            <el-date-picker
              v-model="item.expectedDate"
              type="date"
              placeholder="预计操作日期"
              @change="handlerSearch(item, index, 1)"
            />
          </div>
          <div style="display: flex; justify-content: flex-start; align-items: center;">
            <el-col :span="8" style="white-space: nowrap;" class="font-color">实际操作金额：</el-col>
            <el-col :span="16"><el-input
                        v-model="item.actualAmount" placeholder="实际操作金额" @input="formatActualAmount(item)"
                                         @blur="handlerSearch(item, index, 1)" /></el-col>
          </div>
        </el-col>
      </el-row>
      <el-row style="width: 100%; margin-bottom: 10px; display: flex; justify-content: flex-end; align-items: center;">
        <el-button type="default" class="sub-btn" @click="handlerSearch(item, index,2)">查询</el-button>
        <el-button @click="handlerDelete(item,index)">删除</el-button>
      </el-row>
      <el-row style="width: 100%">
        <el-table :data="item.demandInfoTradingUnitInformationControllers" style="width: 100%">
          <el-table-column label="序号" width="180" align="center" header-align="center">
              <template #default="{ $index }">
                {{ $index + 1 }}
              </template>
             </el-table-column>
          <el-table-column prop="periodStart" width="180" label="时段" align="center" header-align="center">
            <template #default="scope">
              <span :style="{ color: getTimePeriodColor(scope.row.periodStart+'-'+scope.row.periodEnd) }">
                <!-- 修改部分：判断时间是否为 23:00 - 00:00 并转换 -->
               {{ scope.row.periodStart === '23:00' && scope.row.periodEnd === '00:00' ? '23:00 —— 24:00' : scope.row.periodStart + ' —— ' + scope.row.periodEnd }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="kml" width="180" :label="getKmlLabel(item)" align="center" header-align="center" :formatter="(row) => Number(row.kml).toFixed(3)"/>
          <el-table-column prop="zc" width="180" :label="getZcLabel(item)" align="center" header-align="center" :formatter="(row) => Number(row.kml).toFixed(3)"/>
          <el-table-column prop="kmml" width="180" :label="getKmmlLabel(item)" align="center" header-align="center" :formatter="(row) => Number(row.kml).toFixed(3)"/>
          <el-table-column prop="electricity" label="电量MWh" align="center">
            <template #default="scope">
              <el-input-number
style="width: 300px;" v-model="scope.row.electricity" :default-value="0" @change="handleElectricityChange(scope.row, item, index)"
              :controls="false" :min="0" />
            </template>
          </el-table-column>
          <el-table-column prop="electricityPrice" label="电价 元/MWh" align="center" header-align="center">
            <template #default="scope">
              <el-input-number
              style="width: 300px;"
              v-model="scope.row.electricityPrice" :default-value="0" @change="updateActualAmount(scope.row, item, index)" :controls="false" :min="0" />
            </template>
         </el-table-column>
        </el-table>
      </el-row>
    </div>
  </div>
</template>

<style scoped lang="scss">

.sub-btn {
  background-color:  #409eff;
  color: #fff !important;
}

.bg-color {
  background-color:  #409eff !important;
}
.font-color {
  color:  #409eff;
  font-size: 16px;
}

.table-zhuanrang {
  width: 100%;
  padding: 8px 12px;
  background-color: #409eff;
  font-size: 20px;
  font-weight: bold;
  margin: 14px 0;
  color: #fff;
  border-radius: 4px;
}

.shijicaozuo-jine {
  font-weight: bold;
  margin: 10px 0;
}

.caozuo-box {
  width: calc(100% - 40px);
  border-left: 1px dashed #ccc;
  margin-left: 20px;
  padding-left: 20px;
}

.update-time {
  margin: 8px 20px;
}

.caozuo-box-zhuan {
  margin: 8px 20px;
}

.submit-dd {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.custom-small-font {
  font-size: 16px; /* 可按需调整字体大小 */
}
</style>
